# encoding:gbk
import os
import time

__author__ = 'cuizhichao'
from SGMLParser4A import ListName
from urllib import unquote
import string

# 目录名的二次反编码
def dencodename(str):
    tmp = unquote(unquote(str)).decode('utf8')
    tmp = string.replace(tmp, '%', '')
    return tmp

# 转为标准编码
def replacechar(str1):
    tmp1 = string.replace(str1, '_25', '%25')
    return tmp1

# 获取htm中的文件名对应关系
def do_file(file_path):
    # print '&&&&', file_path
    with open(file_path) as fn:
        content = fn.read()
    list_name = ListName()
    list_name.feed(content)
    if list_name.name:
        return list_name.name
    else:
        return {}

# 重命名
def rename(path, old_name, new_name):
    global count
    i = '1'
    old_path = os.path.join(path, old_name)
    # 重名的文件，对名称进行修改
    while True:
        if os.path.exists(os.path.join(path, new_name.encode('gbk'))):
            new_name = i + new_name
        else:
            break
    new_path = os.path.join(path, new_name.encode('gbk'))
    print '******'
    count += 1
    # os.chdir(path)
    try:
        os.rename(old_path, new_path)
    except:
        # 很多文件重命名报错  winException error 2,但是名称已改
        print old_path
        print new_path


def write_log(log_path, msg):
    try:
        with open(log_path, 'a') as f:
            f.writelines(msg + '\n')
    except:
        print 'write log error'


def do_run(path):
    htms = []       # 存放htm文件，里面有其它文件的名称对应关系
    others = []     # 存放待重命名的文件
    dirs = []       # 存放目录
    tmp = []        # 存放被修改的文件
    global total
    global exnames

    # 列出当前目录中的各种文件
    for filename in os.listdir(path):
        full_path = os.path.join(path, filename)
        if os.path.isdir(full_path):
            dirs.append(filename)
        elif full_path.endswith('.htm'):
            htms.append(filename)
        else:
            others.append(filename)

    # 先用了下面的方法修改了目录名，所以没用htm文件中的关联信息处理目录名
    for filename in dirs:
        full_path = os.path.join(path, filename)
        if os.path.isdir(full_path):
            do_run(full_path)
            filename = replacechar(filename)
            filename = dencodename(filename)
            new_path = os.path.join(path, filename)
            print '#########'
            try:
                os.rename(full_path, new_path)
            except:
                print full_path
                print new_path

    for filename in htms:
        full_path = os.path.join(path, filename)
        new_names = do_file(full_path)
        # 有些文件的名称对应关系不在同目录下的htm文件中，而在子目录中的某个htm文件中，
        # 所以先将子目录里的htm文件对应关系收集起来在处理当前目录的文件
        total.update(new_names)
        for other_name in others:
            # 不包含“_25”的文件不处理
            if '_25' not in other_name:
                continue
            if other_name in total:
                tmp.append(other_name)
                new_name = total[other_name]
                rename(path, other_name, new_name)
                # others.remove(other_name)
            elif '.' in other_name:
                # 某些对应关系中不包含扩展名，坑
                for exn in exnames:
                    if other_name.endswith(exn):
                        other_name1 = string.replace(other_name, exn, '')
                        if other_name1 in total:
                            tmp.append(other_name)
                            new_name = total[other_name1]
                            rename(path, other_name, new_name)

    # 记录没有重命名的被编码文件
    for other in others:
        if other not in tmp:
            if '_25' in other:
                write_log('useless.log', os.path.join(path, other))


if __name__ == '__main__':
    count = 0          # 记录重命名文件数量
    total = {}         # 记录htm文件中的对应关系， key--文件现有名称，value--真名

    # 扩展名用于某些对应关系中不包含扩展名的情况
    exnames = ['.pdf', '.zip', 'png',
               '.jpg']  # ,'.rar', '.exe', '.doc', '.ppt', 'docx', '.pptx', '.txt', '.tar.gz', '.tar']

    do_run('d:\\Export\\linux.linuxidc.com')
    print count

    
